<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <p>管理系统用户信息</p>
    </div>

    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="searchForm.role"
            placeholder="全部"
            clearable
            @change="handleSearch"
            @clear="handleSearch"
          >
            <el-option label="全部" :value="null" />
            <el-option label="普通用户" :value="0" />
            <el-option label="管理员" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="user-cards" v-loading="loading">
      <div
        v-for="user in userList"
        :key="user.id"
        class="user-card"
      >
        <div class="card-header">
          <div class="user-avatar">
            <div class="avatar-initial" :style="getAvatarStyle(user.username)">
              {{ user.username ? user.username.charAt(0).toUpperCase() : 'U' }}
            </div>
          </div>
          <div class="user-info">
            <h3>{{ user.username }}</h3>
            <p>{{ user.email }}</p>
          </div>
          <div class="user-role">
            <el-tag :type="user.role === 1 ? 'danger' : 'primary'">
              {{ user.role === 1 ? '管理员' : '普通用户' }}
            </el-tag>
          </div>
        </div>

        <div class="card-content">
          <div class="info-row">
            <span class="label">注册时间:</span>
            <span class="value">{{ formatDate(user.createdAt) }}</span>
          </div>
          <div class="info-row">
            <span class="label">最后更新:</span>
            <span class="value">{{ formatDate(user.updatedAt) }}</span>
          </div>
        </div>

        <div class="card-actions">
          <el-button type="primary" size="small" @click="editUser(user)">
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="deleteUser(user)"
            :disabled="user.id === currentUserId"
          >
            删除
          </el-button>
        </div>
      </div>
    </div>

    <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户"
      width="500px"
      :before-close="handleEditClose"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option label="普通用户" :value="0" />
            <el-option label="管理员" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getUserList, updateUser, deleteUser as deleteUserApi } from '@/api/user'

const userStore = useUserStore()

const loading = ref(false)
const saving = ref(false)
const editDialogVisible = ref(false)
const editFormRef = ref()

const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const userList = ref([])
const currentUserId = ref(userStore.userInfo.id)

const searchForm = reactive({
  username: '',
  email: '',
  role: null
})

const editForm = reactive({
  id: null,
  username: '',
  email: '',
  role: 0
})

const editRules = reactive({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
})

onMounted(() => {
  loadUserList()
})

const loadUserList = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      username: searchForm.username || '',
      email: searchForm.email || '',
      role: searchForm.role !== null ? searchForm.role : ''
    }

    const result = await getUserList(params)
    if (result.success) {
      userList.value = result.data.records || []
      total.value = result.data.count || 0
    } else {
      ElMessage.error(result.message || '获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadUserList()
}

const resetSearch = () => {
  searchForm.username = ''
  searchForm.email = ''
  searchForm.role = null
  handleSearch()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadUserList()
}

const editUser = (user) => {
  editForm.id = user.id
  editForm.username = user.username
  editForm.email = user.email
  editForm.role = parseInt(user.role) || 0
  editDialogVisible.value = true
}

const handleEditClose = () => {
  if (editFormRef.value) {
    editFormRef.value.clearValidate()
  }
  editForm.id = null
  editForm.username = ''
  editForm.email = ''
  editForm.role = 0
}

const saveUser = async () => {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()
    saving.value = true

    const result = await updateUser({
      id: editForm.id,
      email: editForm.email,
      role: editForm.role
    })

    if (result.success) {
      ElMessage.success(result.message || '更新成功')
      editDialogVisible.value = false
      loadUserList()
    } else {
      ElMessage.error(result.message || '更新失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await deleteUserApi({ id: user.id })
    if (result.success) {
      ElMessage.success(result.message || '删除成功')
      loadUserList()
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

const getAvatarStyle = (username) => {
  const colors = [
    ['#FFB6C1', '#FFC0CB'], // 浅粉色
    ['#98FB98', '#90EE90'], // 浅绿色
    ['#87CEEB', '#87CEFA'], // 天蓝色
    ['#DDA0DD', '#DA70D6'], // 梅红色
    ['#F0E68C', '#FFE4B5'], // 卡其色
    ['#FFA07A', '#FFB07A'], // 浅橙色
  ]

  if (!username) return { background: 'linear-gradient(135deg, #FFB6C1, #FFC0CB)' }

  const index = username.charCodeAt(0) % colors.length
  const [color1, color2] = colors[index]

  return {
    background: `linear-gradient(135deg, ${color1}, ${color2})`
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h2 {
  color: var(--macaron-dark);
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
}

.page-header p {
  color: #7f8c8d;
  font-size: 14px;
}

.search-section {
  background: var(--macaron-white);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.search-form .el-form-item {
  margin-right: 20px;
  margin-bottom: 0;
}

.search-form .el-input {
  width: 200px;
}

.search-form .el-select {
  width: 120px;
}

.user-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.user-card {
  background: var(--macaron-white);
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.user-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  border-color: var(--macaron-mint);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 15px;
}



.avatar-initial {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 18px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.user-info {
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.user-info h3 {
  color: var(--macaron-dark);
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-info p {
  color: #7f8c8d;
  font-size: 14px;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-role {
  flex-shrink: 0;
  min-width: 80px;
  margin-left: 10px;
}

.card-content {
  margin-bottom: 15px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--macaron-grey);
}

.info-row:last-child {
  border-bottom: none;
}

.info-row .label {
  font-weight: 500;
  color: var(--macaron-dark);
  font-size: 13px;
}

.info-row .value {
  color: #7f8c8d;
  font-size: 13px;
}

.card-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .user-cards {
    grid-template-columns: 1fr;
  }

  .search-form {
    flex-direction: column;
  }

  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
  }

  .search-form .el-input,
  .search-form .el-select {
    width: 100%;
  }

  .card-header {
    flex-direction: column;
    text-align: center;
    gap: 10px;
  }

  .user-info {
    text-align: center;
    min-width: auto;
  }

  .user-info h3,
  .user-info p {
    white-space: normal;
    overflow: visible;
    text-overflow: clip;
  }

  .user-role {
    align-self: center;
    margin-left: 0;
  }
}
</style>